<?php

/**
 * @copyright Michiel Hakvoort 2010
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD
 * @package mangrove
 * @subpackage core
 * @filesource
 */

/*
 * Copyright (c) 2010 Michiel Hakvoort
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

namespace mg;

use ReflectionClass;

/*
 *
 * @author Michiel Hakvoort
 * @version 1.0
 * @see Architecture
 */
class ClassLoader {

    // Import class properties
    const INVOKE_STATIC    = 0x01;

    /**
     * The current amount of loaded classes
     *
     * @var int
     */
    private $classCount = 0;

    // classname -> file
    private $storage = null;

    // static class properties
    private $properties = null;

    /**
     * Instantiate the class loader.
     */
    public function __construct(Architecture $architecture, StorageManager $storageManager) {
        $storage = $storageManager->getStorage('classloader.location', true);
        $this->storage = $storageManager->cache($storage);

        $updates = $architecture->getUpdates();

        /* @var $update ClassUpdate */
        foreach($updates as $update) {
            $className = $update->getQualifiedName();

            if($update->isRemoved()) {
                unset($this->storage[$className]);
                continue;
            }

            $class = $update->getTo();

            if($class->isInternal()) {
                continue;
            }

            $this->storage[$className] = $class->getFile();
        }


    }

    /**
     * Attempts to load the class with the given class name and execute any methods
     * related to the properties of the class being loaded.
     *
     * @param string $className The name of the class to be loaded.
     *
     * @throws ClassNotFoundException when the class could not be found.
     */
    public function load($className) {
        $formattedClassName = mb_strtolower($className);

        // If the class is not known, throw an exception or load the class as a virtual entity
        if(!isset($this->storage[$formattedClassName])) {
            $baseName = $className;
            $namespace = null;

            if(($delimPos = mb_strrpos($className, '\\')) !== false) {
                $baseName = mb_substr($className, $delimPos + 1);
                $namespace = mb_substr($className, 0, $delimPos);
            }

            eval(($namespace === null ? '' : "namespace {$namespace};\n") . "class {$baseName} {}");

            throw new ClassNotFoundException("Class '".$className."' could not be found.");
        }

        $sourceFile = $this->storage[$formattedClassName];

        // Include the sourcefile
        try {
            include($sourceFile);
        } catch(EngineException $e) {
            throw $e;
        }

        // If the sourcefile (somehow) did not contain the class
        if(!(class_exists($className) || interface_exists($className))) {
            $baseName = $className;
            $namespace = null;

            if(($delimPos = mb_strrpos($className, '\\')) !== false) {
                $baseName = mb_substr($className, $delimPos + 1);
                $namespace = mb_substr($className, 0, $delimPos);
            }

            eval(($namespace === null ? '' : "namespace {$namespace};\n") . "class {$baseName} {}");

            throw new ClassNotFoundException("Class '".$className."' could not be found.");

        }

    }
}

function get_class($instance) {
    $className = \get_class($instance);

    if(mb_substr($className, 0, 14) === '__generated__\\') {
        return mb_substr($className, 14);
    }
    return $className;
}